﻿using System;
using System.Xml.Serialization;

// ReSharper disable UnusedMember.Global

namespace LightPersist
{
	// Properties - for xml serializetion
	// Non autoproperties for allowing to initialize it in struct ctor

	public struct Reference
	{
		Guid _id;
		[XmlAttribute]
		public Guid ID
		{
			get { return _id; }
			set { _id = value; }
		}


		Type _typeOfProperty;
		[XmlIgnore]
		public Type TypeOfProperty
		{
			get { return _typeOfProperty; }
		}


		string _cachedPropertyType;
		[XmlAttribute]
		public string PropertyType
		{
			get
			{
				if (_cachedPropertyType == null)
				{
					_cachedPropertyType = TypeOfProperty.AssemblyQualifiedName;
				}
				return _cachedPropertyType;
			}
			set
			{
				_typeOfProperty = Type.GetType(value);
				_cachedPropertyType = null;
			}
		}

		public Reference(Guid id, Type propType)
		{
			_id = id;
			_typeOfProperty = propType;
			_cachedPropertyType = propType.AssemblyQualifiedName;
		}

		public override string ToString()
		{
			return "Ref: " + ID.ToStringDebug();
		}

		public override bool Equals(object obj)
		{
			if (ReferenceEquals(null, obj))
			{
				return false;
			}
			if (obj.GetType() != typeof(Reference))
			{
				return false;
			}
			return Equals((Reference)obj);
		}

		public bool Equals(Reference other)
		{
			return other._id.Equals(_id) && Equals(other._typeOfProperty, _typeOfProperty);
		}

		public override int GetHashCode()
		{
			unchecked
			{
				return (_id.GetHashCode() * 397) ^ (_typeOfProperty != null ? _typeOfProperty.GetHashCode() : 0);
			}
		}
	}

}
